new Vue({
    el: '#app',
    data: {
        // 选择分类加载中
        loadingSelectCategory: false,
        // 表格加载中
        loadingTable: false,
        // 用户信息
        userInfo: userInfo != null ? userInfo : {
            id: null,
            nickname: "未登录"
        },
        // 是否显示添加笔记的输入框
        showAddNoteCard: false,
        // 题型
        questionKinds: ['选择题', '填空题', '判断题', '解答题'],
        // 题目表格中的数据
        tableQuestions: [{
            // 题目类型
            kindInt: 0,
            // 题目类型（字符串）
            kind: '选择题',
            // 题目内容
            question: 'data[i].question',
            // id
            id: 'data[i].id',
            // 选项内容（列表）
            choice: ['choices', '2'],
            // 答案（字符串列表）
            answer: ['AB'],
            // 状态
            status: 1,
            // 创建者id
            creator: 'data[i].creator',
            // 是否公开
            open: 'open',
            // 所属分类信息List<Category>
            categories: 'data[i].categories',
            // 所属分类名
            category: 'categoryNamesOfAQuestion'
        }],
        // 输入题目内容（用于查询）
        inputQuestion: '',
        // 已经选择的分类（id）
        selectedCategories: [],
        // 查询到的分类{ id: 1,name: '分类1',creator: 1,nickname: '用户1'}
        categories: [],
        // 要查询的题型
        checkboxQuestions: [],
        // 抽屉显示
        drawerDetails: false,
        // 当前题目详情
        currentQuestion: {},
        // 当前题目的笔记
        currentNotes: [{}],
        // 新增笔记
        note: {
            content: '',
            open: false
        },
        openStatus: ['不公开', '公开'],
        choiceOfAlpha: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'],
        curPrefixUrl: prefixUrl + gatewayPrefix.question,
        scrollContainer: null,
        debouncedHandleScroll: null,
        lastQuestionId: null,
    },
    methods: {
        // 查询题目
        query() {
            console.log("selectedCategories=" + JSON.stringify(this.selectedCategories));
            console.log("inputQuestion=" + this.inputQuestion);
            // console.log("tableQuestions=" + JSON.stringify(this.tableQuestions));
            this.getAllQuestionByCondition();
        },
        // 查看题目详情
        seeDetail(row) {
            this.currentQuestion = row;
            this.drawerDetails = true;

            // 获取笔记
            this.getNotesByQuestionId(this.currentQuestion.id);
        },
        // 多选框选中
        handleSelectionChange(val) {
            this.selectedQuestion = val;
            console.log("this.selectedQuestion=" + JSON.stringify(this.selectedQuestion))
        },
        // 查询分类
        queryCategories(string) {
            // 先清空
            this.categories = [];
            this.loadingSelectCategory = true;
            console.log("string=" + string);
            const url = this.curPrefixUrl + "/user/categories/name/" + string;
            axios.get(url).then((resp) => {
                const result = resp.data;

                this.categories = result.data;
            }).finally(() => {
                this.loadingSelectCategory = false;
            });
        },
        // 条件查询我的题目（题目内容、分类）
        getAllQuestionByCondition() {
            this.tableQuestions = [];
            this.loadingTable = true;
            const url = this.curPrefixUrl + "/user/questions/condition/all";

            const questionQueryDTO = {
                question: this.inputQuestion,
                categoryIds: this.selectedCategories,
                kinds: this.checkboxQuestions
            }
            console.log("questionQueryDTO=" + JSON.stringify(questionQueryDTO));
            axios.post(url, questionQueryDTO).then((resp) => {
                const result = resp.data;

                // data：ChoiceQuestionVO
                const data = result.data;
                // 添加数据到表格中
                this.addQuestionToTable(data);
            }).finally(() => {
                this.loadingTable = false;
            });
        },
        loadQuestion() {
            this.loadingTable = true;
            const url = this.curPrefixUrl + "/user/questions/condition/all";

            const questionQueryDTO = {
                id: this.lastQuestionId,
                question: this.inputQuestion,
                categoryIds: this.selectedCategories,
                kinds: this.checkboxQuestions
            }
            console.log("questionQueryDTO=" + JSON.stringify(questionQueryDTO));
            axios.post(url, questionQueryDTO).then((resp) => {
                const result = resp.data;

                // data：ChoiceQuestionVO
                const data = result.data;
                if (data.length === 0) {
                    showMsg(this, "没有更多题目了~");
                }
                // 添加数据到表格中
                this.addQuestionToTable(data);
            }).finally(() => {
                this.loadingTable = false;
            });
        },
        // 添加数据到表格中
        addQuestionToTable(data) {
            for (let i = 0; i < data.length; i++) {
                if (i === data.length - 1) {
                    this.lastQuestionId = data[i].id;
                    console.log("this.lastQuestionId=" + this.lastQuestionId);
                }
                const categories = data[i].categories;
                // 获取分类名
                let categoryNamesOfAQuestion = '';
                if (categories.length !== 0) {
                    categoryNamesOfAQuestion = categories[0].name;
                    for (let j = 1; j < categories.length; j++) {
                        const categoryNameOfAQuestion = categories[j].name;
                        categoryNamesOfAQuestion += ('、' + categoryNameOfAQuestion);
                    }
                }
                // 答案
                let answer = [data[i].answer.trim()];
                // 选项
                let choices;
                // 选择题
                if (data[i].kind === questionKind.choice) {
                    choices = data[i].choice.trim().split(split.default);
                    let tempAns = '';
                    for (let i = 0; i < answer[0].length; i++) {
                        tempAns += optoins[parseInt(answer[0].at(i))];
                    }
                    answer = [tempAns];
                }
                // 判断题
                else if (data[i].kind === questionKind.judge) {
                    if (answer[0] === '0') {
                        answer = [judge.yes];
                    } else {
                        answer = [judge.no];
                    }
                }
                // 填空题
                else if (data[i].kind === questionKind.blank) {
                    answer = data[i].answer.trim().split(split.default);
                }
                // 是否公开
                let open;
                if (data[i].open === openStatus.open) {
                    open = openStatus.yes;
                } else {
                    open = openStatus.no;
                }
                this.tableQuestions.push({
                    // 题目类型
                    kindInt: data[i].kind,
                    // 题目类型
                    kind: this.questionKinds[data[i].kind],
                    // 题目内容
                    question: data[i].question,
                    // id
                    id: data[i].id,
                    // 选项内容
                    choice: choices,
                    // 答案
                    answer: answer,
                    // 状态
                    status: data[i].status,
                    // 创建者id
                    creator: data[i].creator,
                    // 是否公开
                    open: open,
                    // 所属分类信息
                    categories: data[i].categories,
                    // 所属分类名
                    category: categoryNamesOfAQuestion
                });
            }
        },
        // 获取题目对应的笔记
        getNotesByQuestionId(questionId) {
            const url = prefixUrl + "/note/user/notes/" + questionId;
            axios.get(url).then((resp) => {
                const result = resp.data;

                this.currentNotes = result.data;
                console.log("currentNotes=" + JSON.stringify(this.currentNotes));
            }).catch(() => {
            }).finally(() => {
            });
        },
        // 修改笔记
        editNote(id) {
            showAlert(this, id);
        },
        // 展示添加笔记卡片
        showAddNote() {
            this.showAddNoteCard = !this.showAddNoteCard;
        },
        // 添加笔记
        addNote() {
            let noteAddDTO = {
                questionId: this.currentQuestion.id,
                content: this.note.content,
                open: openStatus.notOpen
            };
            if (this.note.open) {
                noteAddDTO.open = openStatus.open;
            }

            const url = prefixUrl + "/note/user/notes";
            // 加载
            this.loadingAddNote = true;
            axios.post(url, noteAddDTO).then((resp) => {
                const result = resp.data;

                if (result.code === resultConstant.success) {
                    // 清空
                    this.note = {};
                    // 提示
                    showSuccessMsg(this, "笔记添加成功");
                    // 查询笔记
                    this.getNotesByQuestionId(this.currentQuestion.id);
                } else {
                    showErrorMsg(this, result.msg);
                }
            }).catch(() => {
            }).finally(() => {
                this.loadingAddNote = false;
            });
        },
        // 关闭题目详情
        closeDrawerDetails() {
            this.drawerDetails = false;
            this.currentQuestion = {};
            this.showAddNoteCard = false;
            this.note = {};
        },
        // el-table是否滚动到了最底部
        isScrolledToBottom() {
            this.scrollContainer = this.$refs.questionTable.$el.querySelector('.el-table__body-wrapper');
            if (this.scrollContainer) {
                const {scrollTop, scrollHeight, clientHeight} = this.scrollContainer;
                return scrollTop + clientHeight >= scrollHeight - 1;
            }
            return false;
        },
        handleScroll() {
            // console.log("scrollTop=" + this.scrollContainer.scrollTop);
            // console.log("scrollHeight=" + this.scrollContainer.scrollHeight);
            // console.log("clientHeight=" + this.scrollContainer.clientHeight);
            if (this.isScrolledToBottom()) {
                // 滚动到底部时执行的操作
                console.log("isScrolledToBottom");
                this.loadQuestion();
            }
            // else {
            //     console.log("not isScrolledToBottom");
            // }
        },
        my_debounce(func, wait) {
            if (typeof func !== 'function') {
                throw new TypeError('need a function');
            }
            wait = +wait || 0;

            let timeId = null;

            return function () {
                // console.log('滚动了滚动了');  // 测试时可放开
                const self = this;
                const args = arguments;

                if (timeId) {
                    clearTimeout(timeId);   // 清除定时器，重新设定一个新的定时器
                }
                timeId = setTimeout(() => {
                    func.apply(self, args); // arguments 是传给函数的参数，这里是 event  对象
                }, wait);
            }
        }
    },
    created() {
        saveSessionStorage(this, storageKey.allQuestionData, () => {
            this.getAllQuestionByCondition();
        })
    },
    mounted() {
        // 获取el-table的scrollContainer
        this.scrollContainer = this.$refs.questionTable.$el.querySelector('.el-table__body-wrapper');
        // 监听滚动事件
        // 使用防抖技术限制 handleScroll 的执行频率
        this.debouncedHandleScroll = this.my_debounce(this.handleScroll, 100);
        this.$nextTick(() => {
            this.scrollContainer.addEventListener('scroll', this.debouncedHandleScroll);
        });
    },
    beforeDestroy() {
        this.scrollContainer.removeEventListener('scroll', this.debouncedHandleScroll);
    }
});